﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Owin
{
    using Jhong.FunMVC;
    using Microsoft.Owin;
    using Owin;
    using System.Reflection;

    public static class FunMVCMiddleware
    {

        public static FunMVCExtension UseFunMVC(this IAppBuilder app)
        {
            return app.UseFunMVC(new FunMVCOption());
        }

        public static FunMVCExtension UseFunMVC(this IAppBuilder app, FunMVCOption option)
        {

            //注册路由
            Type routeClass = null;
            foreach (var i1 in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var i2 in i1.GetTypes())
                {
                    foreach (var i3 in i2.GetInterfaces())
                    {
                        if (false == i3.Name.Equals(typeof(IRoutes).Name))
                            continue;
                        routeClass = i2;
                        break;
                    }
                }
            }
            if (null != routeClass)
            {
                var rcInstance = Activator.CreateInstance(routeClass) as IRoutes;
                rcInstance.RegisterRoutes();
            }
            //option
            FunMVCOption.FMOption = option;

            app.Run(context =>
            {
                var handler = new RouteHandler(context);
                return handler.Hand();
            });
            var instance = FunMVCExtension.GetMVCExtensionInstance();
            instance.APPBuilder = app;
            instance.Option = new FunMVCExtensionOption();
            return instance;
        }

    }





    public class FunMVCExtension
    {
        private FunMVCExtension() { }

        private static FunMVCExtension _instance;

        private static object _lock = new object();

        public static FunMVCExtension GetMVCExtensionInstance()
        {
            lock (_lock)
            {
                if (null == _instance) _instance = new FunMVCExtension();
                return _instance;
            }
        }

        public IAppBuilder APPBuilder { get; set; }

        public FunMVCExtensionOption Option { get; set; }
    }



}
